# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: leon

import datetime
import json
import logging
import os
import io
from concurrent.futures import ProcessPoolExecutor

from absl import (app, flags)

from coin.proto.coin_order_gateway_pb2 import OrderGatewayLog
from coin.exchange.base.order_gateway_logger import parse_file_name
from coin.support.proto_log.logic.util import (run_from_og_log_archive,
                                               enumerate_og_log_into_oginfos)

FLAGS = flags.FLAGS


class OnLog(object):
  def __init__(self):
    self._symbol = set()

  @property
  def symbol(self):
    return self._symbol

  def on_log(self, timestamp, log):
    pb = OrderGatewayLog()
    pb.ParseFromString(log)
    if pb.type == OrderGatewayLog.SUBMIT_REQUEST:
      request = pb.submit_request
      symbol = request.symbol
      self._symbol.add(symbol)


def launch(owner, market_type, exchange, trading_date, root_dir, machine, og_log):
  start_time = trading_date  # UTC 0 hour
  hours = 24

  strategy = OnLog()
  run_from_og_log_archive(strategy.on_log,
                          market_type,
                          exchange,
                          start_time,
                          start_time + datetime.timedelta(hours=hours),
                          root_dir,
                          machine,
                          owner=owner)
  output = io.StringIO()
  print(json.dumps(og_log._asdict(), indent=4), file=output)
  print(list(strategy.symbol), file=output)
  print('================================================================', file=output)
  print(output.getvalue())
  output.close()
  return strategy.symbol


def main(_):
  trading_date = FLAGS.trading_date
  assert trading_date, '--trading_date must be specified.'
  root_dir = os.path.expanduser('/remote/iosg/strat-1/buckets/log.raw.coin/live/og_proto_log/')

  print('Run for %s:\n' % trading_date)
  og_infos = enumerate_og_log_into_oginfos(root_dir, trading_date, parse_file_name)
  trading_date = datetime.datetime.strptime(trading_date, '%Y%m%d')

  symbols = set()
  futures = []
  with ProcessPoolExecutor(max_workers=12) as executor:
    for og_info in og_infos:
      future = executor.submit(launch,
                               og_info.owner,
                               og_info.market_type,
                               og_info.exchange,
                               trading_date,
                               root_dir,
                               og_info.machine,
                               og_info)
      futures.append(future)
    for future in futures:
      symbols.update(future.result())
    print(symbols)


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'Trading date in form of %Y%m%d.')

  logging.basicConfig(level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  app.run(main)
